<?php

namespace app\model\v1\gift;

use app\model\order\StoreOrder;
use app\model\user\User;
use app\model\user\UserBill;
use app\model\user\UserMoney;
use app\model\v1\recovery\RecoveryProduct;
use app\model\v1\recruit\RecruitPersonageAuthentication;
use crmeb\traits\ModelTrait;
use think\Exception;
use think\facade\Db;
use think\Model;


class GiftCardUser extends Model
{

    use ModelTrait;

    protected $updateTime = false;
    protected $createTime = false;

    protected $hidden = [
   //     'create_time','update_time','delete_time'
    ];

    protected $table = 'eb_gift_card_user';

    const  ENCRYPTID = 'gift_card_user';



    public function giftcard()
    {
        return $this->hasOne(GiftCard::class, 'id', 'gift_card_id');
    }

    public function user()
    {
        return $this->hasOne(User::class, 'uid', 'uid');
    }


    public function storeorder()
    {
        return $this->hasOne(StoreOrder::class, 'order_id', 'order_id');
    }


    public function shareinfo()
    {
        return $this->hasOne(GiftShareInfo::class, 'card_user_id', 'id');
    }

    public function sharelog()
    {
        return $this->hasOne(GiftCardShareLog::class, 'card_user_id', 'id');
    }


    /**
     * 礼品卡激活/领取
     * @param array $param
     * @return GiftCardUser
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function activeGiftCard(array $param)
    {
        $find = self::where("id", $param['id'])->find();

        $update = [
            "number"=>$param["number"],
            "card_pwd"=>$param['card_pwd'],
            "update_time"=>time()
        ];
        try {
            Db::startTrans();

            $type = 1;
            if($param['rec_type'] == 1) {  //领取
                if($find["is_rec"] == 2) Throw new Exception('已领取，不能重复领取！');
                if($find['uid'] == $param['uid']) Throw new Exception('不能自己领取！');

                $update["is_rec"] = 2;
                $update["type"] = 3;
                $update["rec_time"] = time();
                $type = 4;

                $add = [
                    "uid" => $param['uid'], //用户id
                    "gift_card_id" => $find['gift_card_id'],
                    "order_id" => $find['order_id'],
                    "number" => $find['number'],
                    "card_pwd" => $find['card_pwd'],
                    "bless" => $find['bless'],
                    "price_text" => $find['price_text'],
                    "type" => 2,
                    "type_bak" => 2,
                    "is_rec" => 1,
                    "create_time" => time(),
                ];
                self::create($add);


            } else if($param['rec_type'] == 2) {  //激活
                $reg_find = RecruitPersonageAuthentication::where(["u_id"=>$param["uid"]])->whereNull("delete_at")->find();
                if(empty($reg_find))  throw new Exception("请先实名认证！");
                if(!empty($find["status"])){
                    if($find["status"] == 1) {
                        throw new Exception("审核中，请实名审核通过后再发布！");
                    }else if($find["status"] == 3) {
                        throw new Exception("审核未通过，请实名认证审核！");
                    }
                }

                if($find["status"] == 1) Throw new Exception('已激活，不能重复激活！');
                if($param["number"] != $find["number"]) Throw new Exception('卡号错误');
                if($param["card_pwd"] != $find["card_pwd"]) Throw new Exception('密码错误');

                $update["status"] = 1;
                $update["act_time"] = time();

                //添加余额
                //$user = Db::name('user')->where('uid',$param['uid'])->find();
                //Db::name('user')->where('uid',$param['uid'])->inc('now_money',$find['price_text'])->update();
                $price_find = self::getGiftCardPrice($find['number']);
                $price_text = $price_find["price"] ?? 0;  //GiftCardUser::where("number", $param['number'])->value("price_text") ?? 0;
                $user = Db::name('user')->where('uid',$param['uid'])->find();
                Db::name('user')->where('uid',$param['uid'])->inc('now_money',$price_text)->update();

                RecoveryProduct::updateUserNowMoney($user["phone"], $price_text);

                $add = [
                    'uid' => $param['uid'],
                    'pm' => 1,
                    'title' => '礼品卡激活添加余额',
                    'category' => 'gift',
                    'type' => 'gift_act',
                    'number' => $price_text, //$find['price_text'],
                    'balance' => $user["now_money"] ?? 0 + $price_text, //$find['price_text'],
                    'mark' => '用户礼品卡激活添加余额'. $price_text.'元',    //$find['price_text']
                    'add_time' => time(),
                ];
                UserBill::create($add);

                $add_bill = $add;
                unset($add_bill["add_time"]);
                unset($add_bill["balance"]);
                $add_bill["create_time"] = date("Y-m-d H:i:s");
                RecoveryProduct::syncUserBill($add_bill);

                $add = [
                    'uid' => $param['uid'],
                    'link_id' => 2,
                    'type' => 'gift_act',
                    'title' => '礼品卡激活添加余额',
                    'number' => $price_text, //$find['price_text'],
                    'balance' => $user["now_money"] ?? 0 + $price_text, //$find['price_text'],
                    'pm' => 1,
                    'mark' => '用户礼品卡激活添加余额'.$price_text.'元',     //$find['price_text']
                    'add_time' => time(),
                ];
                UserMoney::create($add);
            }

            $res = self::where("id", $param['id'])->update($update);

            $add = [
                "uid" => $param['uid'], //用户id
                "card_user_id" => $param['id'],
                "type" => $type,
                "create_time" => time(),
            ];
            GiftCardReport::create($add);

            Db::commit();
        }catch (\Throwable $e){
            Db::rollback();
            Throw new Exception($e->getMessage());
        }

        return $res;
    }


    /**
     * 礼品卡挂失
     * @param array $param
     * @return GiftCardUser
     */
    public static function reportGiftCard(array $param)
    {
        try {
            Db::startTrans();
            if(empty($param["card_user_id"])){
                $res = GiftCardUser::where("number", $param["number"])->update(["status" => 2, "reason"=>$param["reason"]]);
            }else{
                $res = GiftCardUser::where("id", $param["card_user_id"])->update(["status" => 2, "reason"=>$param["reason"]]);
            }

            $gift_card_user = GiftCardUser::where("number", $param["number"])->find() ?? [];
            $card_user_id = $gift_card_user["id"] ?? null;

            if(!empty($param['idcard'])){
                if (!check_card($param['idcard'])) throw new Exception( '请填写正确的身份证号码');
            }
            if (!check_phone($param['phone'])) throw new Exception( '请填写正确的手机号');

            if(!empty(GiftCardReport::where("card_user_id", $card_user_id)->find())){
                Throw new Exception("不能重复提交挂失！");
            }
            $add = [
                "uid" => $param['uid'], //用户id
                "card_user_id" => $card_user_id,
                "order_id" => $gift_card_user['order_id'] ?? null,
                "type" => 2,
                "content" => $param['reason'],
                "phone" => $param['phone'],
                "user_name" => $param['user_name'],
                "idcard" => $param['idcard'] ?? '',
                "create_time" => time(),
            ];
            GiftCardReport::create($add);
            Db::commit();

        }catch (\Throwable $e){
            Db::rollback();
            Throw new Exception($e->getMessage());
        }

        return $res;
    }


    /**
     * 挂失补卡
     * @param array $param
     * @return GiftCardUser
     * @throws Exception
     */
    public static function resetGiftCard(array $param)
    {
        try {
            Db::startTrans();
            $res = self::where("id", $param["card_user_id"])->update(['status' => 3, 'address_id' => $param['address_id']]);

            $add = [
                "uid" => $param['uid'], //用户id
                "card_user_id" => $param['card_user_id'],
                "type" => 3,
                "create_time" => time(),
            ];
            GiftCardReport::create($add);

            Db::commit();
        }catch (\Throwable $e){
            Db::rollback();
            Throw new Exception($e->getMessage());
        }
        return $res;
    }


    /**
     * 全部订单列表 - 确认收货
     * @param array $param
     * @return StoreOrder
     */
    public static function confirmGiftCard(array $param)
    {
        $res = StoreOrder::where("order_id", $param["order_id"])->update(["status"=>2]);
        return $res;
    }


    /**
     * 我的礼品卡列表
     * @param int $uid
     * @param array $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGiftCardData(int $uid, array $param)
    {
        $data["data"] = self::alias("a")->field("a.*, FROM_UNIXTIME(a.create_time) as create_time")
            ->with([
                'giftcard' => function ($query) {
                    $query->field('*');
                },
                'storeorder' => function ($query) {
                    $query->field('id,order_id,pay_time,paid,FROM_UNIXTIME(add_time) as add_time,FROM_UNIXTIME(pay_time,"%Y/%m/%d %H:%i:%s") as pay_time');
                },
                'shareinfo' => function ($query) {
                    $query->whereNull("delete_time")->field('*');
                },
            ])
            ->join ('store_order b','a.order_id=b.order_id','left')
            ->whereNull("a.delete_time")
            ->where("a.uid", $uid)
            ->where("a.is_rec", 1)
            ->where("b.paid", 1)
            ->where(function ($query) use ($param){
                if(!empty($param["type"])) $query->where("a.type", $param["type"]);  //1购买 2收到 3送出  4订单取消购买
                if(!empty($param["card_type"])) $query->where("a.card_type", $param["card_type"]);
            })
            ->page($param["page"], $param["limit"])
            ->order('a.id','desc')
            ->select()
            ->toArray();

        $data["count"] = self::alias("a")->field("a.*")
            ->with([
                'giftcard' => function ($query) {
                    $query->field('*');
                },
                'storeorder' => function ($query) {
                    $query->field('id,order_id,pay_time,paid,FROM_UNIXTIME(add_time) as add_time');
                },
            ])
            ->join ('store_order b','a.order_id=b.order_id','left')
            ->whereNull("a.delete_time")
            ->where("a.uid", $uid)
            ->where("a.is_rec", 1)
            ->where("b.paid", 1)
            ->where(function ($query) use ($param){
                if(!empty($param["type"])) $query->where("a.type", $param["type"]);  //1购买 2收到 3送出  4订单取消购买
                if(!empty($param["card_type"])) $query->where("a.card_type", $param["card_type"]);
            })
            ->count();


        if(!empty($data['data'])){
            foreach ($data['data'] as $key => &$val){
                $val["encryptID"] = md5($val['id'] . GiftCardUser::ENCRYPTID);
                $val["card_bless"] = GiftCardBless::getBlessData($val["giftcard"]["tag_id"] ?? 0);
                ////$val["card_pwd"] = "******";
                $val["card_pwd"] = self::encryptcode($val["card_pwd"]);

                if(!empty($val["giftcard"]["tag_id"])){
                    $tag_data = GiftCardCate::getGiftCardMold($val["giftcard"]["tag_id"]);
                    $val["mold"] = $tag_data['mold'] ?? '';
                    $val["head_img"] = $tag_data['head_img'] ?? '';
                    $val["upper_img"] = $tag_data['upper_img'] ?? '';
                    $val["centre_img"] = $tag_data['centre_img'] ?? '';
                    $val["bottom_img"] = $tag_data['bottom_img'] ?? '';
                    $val["bless_img"] = $tag_data['bless_img'] ?? '';
                    $val["img1"] = $tag_data['img1'] ?? '';
                    $val["img2"] = $tag_data['img2'] ?? '';
                    $val["img3"] = $tag_data['img3'] ?? '';
                    $val["img4"] = $tag_data['img4'] ?? '';
                    $val["img5"] = $tag_data['img5'] ?? '';
                    $val["img6"] = $tag_data['img6'] ?? '';
                    $val["img7"] = $tag_data['img7'] ?? '';
                    $val["img8"] = $tag_data['img8'] ?? '';
                    $val["img9"] = $tag_data['img9'] ?? '';
                    $val["img10"] = $tag_data['img10'] ?? '';
                }
            }
        }

        return $data;
    }




    //加密函数
    public static function encryptcode($code)
    {
        static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
        $num = $code;
        $code = '';
        while ($num > 0) {
            $mod = $num % 35;
            $num = ($num - $mod) / 35;
            $code = $source_string[$mod] . $code;
        }
        if (empty($code[3]))
            $code = str_pad($code, 4, '0', STR_PAD_LEFT);
        return $code;
    }

    //解密函数
    public static function decryptcode($code) {
        static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
        if (strrpos($code, '0') !== false)
            $code = substr($code, strrpos($code, '0')+1);
        $len = strlen($code);
        $code = strrev($code);
        $num = 0;
        for ($i=0; $i < $len; $i++) {
            $num += strpos($source_string, $code[$i]) * pow(35, $i);
        }
        return $num;
    }


    public static function getGiftCardDataOrder($uid='', $param=[])
    {
        return self::alias("a")->field("a.*, FROM_UNIXTIME(a.create_time) as create_time")
            ->with([
                'giftcard' => function ($query) {
                    $query->field('*');
                },
                'storeorder' => function ($query) {
                    $query->field('id,order_id,pay_time,paid,FROM_UNIXTIME(add_time) as add_time,FROM_UNIXTIME(pay_time) as pay_time');
                },
                'shareinfo' => function ($query) {
                    $query->whereNull("delete_time")->field('*');
                },
            ])
            ->join('store_order b', 'a.order_id=b.order_id', 'left')
            //->whereNull("a.delete_time")
            ->where("a.uid", $uid)
            //->where("a.is_rec", 1)
            ->where("b.paid", 1)
            ->where(function ($query) use ($param) {
                if (!empty($param["type"])) $query->where("a.type", $param["type"]);  //1购买 2收到 3送出  4订单取消购买
                if (!empty($param["card_type"])) $query->where("a.card_type", $param["card_type"]);
                if (!empty($param["order_id"])) $query->where("a.order_id", $param["order_id"]);
            })
            ->order('a.id', 'desc')
            ->select()
            ->each(function (&$item) {
                ////if(!empty($item['card_pwd'])) $item['card_pwd'] = '******';
                if(!empty($item['card_pwd'])) $item['card_pwd'] = self::encryptcode($item['card_pwd']);
            })
            ->toArray();
    }



    /**
     * 赠送记录列表
     * @param int $uid
     * @param array $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGiftCardRecord(int $uid, array $param)
    {
        if(empty($param["type"])) $param["type"] = 3;  //我送出的

        $data["data"] = self::field("*, FROM_UNIXTIME(create_time) as create_time")
            ->with([
                'giftcard' => function ($query) {
                    $query->field('*');
                },
                'storeorder' => function ($query) {
                    $query->field('id,order_id,pay_time,FROM_UNIXTIME(add_time) as add_time');
                },
                'sharelog' => function ($query) {
                    $query->field('id,card_user_id,uid,FROM_UNIXTIME(create_time) as create_time');
                },
            ])
            ->whereNull("delete_time")
            ->where("uid", $uid)
            ->where(function ($query) use ($param){
                if(!empty($param["type"])) $query->where("type", $param["type"]);  //2收到 3送出
            })
            ->page($param["page"], $param["limit"])
            ->order('id','desc')
            ->select()
            ->toArray();

        $data["count"] = self::field("*")
            ->with([
                'giftcard' => function ($query) {
                    $query->field('*');
                }
            ])
            ->whereNull("delete_time")
            ->where("uid", $uid)
            ->where(function ($query) use ($param){
                if(!empty($param["type"])) $query->where("type", $param["type"]);
            })
            ->count();

        if(!empty($data['data'])){
            foreach ($data['data'] as $key => &$val){
                if(!empty($val["storeorder"])){
                    $val["storeorder"]['pay_time'] = $val["storeorder"]['pay_time'] ? date("Y/m/d H:i:s", $val["storeorder"]['pay_time']) : $val["storeorder"]['pay_time'];
                }

                //if(!empty($val["create_time"])) $val['create_time'] = date("Y/m/d H:i:s", $val['create_time']);
                if(!empty($val["rec_time"])) $val['rec_time'] = date("Y-m-d H:i:s", $val['rec_time']);
            }
        }

        return $data;
    }



    /**
     * 礼品卡挂失-校验卡号
     * @param array $param
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function reportCheckNumber(array $param)
    {
        $find = self::where("uid", $param["uid"])->where('number', $param['number'])->find();
        if(!empty($find)) return true;
        return false;
    }



    /**
     * 礼品卡后台 - 购卡管理列表
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGiftUserList($param = [])
    {
        $data["data"] = self::field ("*,FROM_UNIXTIME(create_time) as create_time,FROM_UNIXTIME(rec_time) as rec_time, 
                 case when type=1 then '购买' 
                    when type=2 then '收到' 
                    when type=3 then '送出' 
                    when type=4 then '订单取消购买' 
                    end as type_text,
                 case when status=0 then '待激活'
                    when status=1 then '已激活' 
                    when status=2 then '已挂失' 
                    when status=3 then '已申请补卡' 
                    end as status_text
            ")
            ->with([
                'giftcard' => function ($query) {
                    $query->field('id,title,price,img');
                },
                'user' => function ($query) {
                    $query->field('uid,nickname,phone,real_name');
                }
            ])
            ->whereNull("delete_time")
            ->where(function ($query) use ($param){
                if(!empty($param['time'])){
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("number",'like', '%'.$param["word"].'%');
            })
            ->order("id", "desc")
            ->page($param['page'], $param['limit'])
            ->select()->toArray();

        $data["count"] = self::field ("*")
            ->whereNull("delete_time")
            ->where(function ($query) use ($param){
                if(!empty($param['time'])){
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("number",'like', '%'.$param["word"].'%');
            })
            ->count();

        return $data;
    }


    /**
     * 购卡管理列表 - 查看
     * @param $param
     * @return GiftCardUser|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detailGiftUser($param = [])
    {
        $data = self::field ("*,FROM_UNIXTIME(create_time) as create_time,FROM_UNIXTIME(rec_time) as rec_time, 
                 case when type=1 then '购买' 
                    when type=2 then '收到' 
                    when type=3 then '送出' 
                    when type=4 then '订单取消购买' 
                    end as type_text,
                 case when status=0 then '待激活'
                    when status=1 then '已激活' 
                    when status=2 then '已挂失' 
                    when status=3 then '已申请补卡' 
                    end as status_text
            ")
            ->with([
                'giftcard' => function ($query) {
                    $query->field('id,title,price,img');
                },
                'user' => function ($query) {
                    $query->field('uid,nickname,phone,real_name');
                }
            ])
            ->where("id", $param["id"])
            ->find();

        return $data;
    }



    /**
     * 购卡管理列表 - 启用禁用
     * @param $param
     * @return string
     */
    public static function enableGiftUser($param = [])
    {
        //获取用户发送的id，根据状态修改当前banner的启用禁用状态
        $status = self::where("id", $param['id'])->value("active");
        $msg = '';
        if($status == 1){   //1启用 2禁用
            $enable = 2;
            $msg = "禁用成功";
        }else{
            $enable = 1;
            $msg = "启用成功";
        }
        self::where("id", $param['id'])->update(['active' => $enable]);
        return $msg;
    }




    /**
     * 购卡管理列表 - 编辑
     * @param $param
     * @return RecruitLanguage
     */
    public static function updateGiftUser($param = [])
    {
        $update["update_time"] = time();  //更新时间
        if(!empty($param["bless"]))         $update["bless"] = $param["bless"];
        if(!empty($param["card_pwd"]))      $update["card_pwd"] = $param["card_pwd"];

        return self::where("id", $param["id"])->update($update);
    }


    /**
     * 礼品卡后台 - 赠送管理列表
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGiftCardShareList($param = [])
    {
        $data["data"] = self::field ("*,FROM_UNIXTIME(create_time) as create_time,FROM_UNIXTIME(act_time) as act_time,
                case when type=1 then '购买' 
                    when type=2 then '收到' 
                    when type=3 then '送出' 
                    when type=4 then '订单取消购买' 
                    end as type_text,
                case when is_rec=1 then '未领取' 
                    when is_rec=2 then '已领取' 
                    end as rec_text
            ")
            ->with([
                'shareinfo' => function($query) {
                    $query->order("id","desc")->field("*");
                },
                'user' => function($query) {
                    $query->field("uid,nickname,real_name,phone");
                }
            ])
            ->whereNull("delete_time")
            ->where(function ($query) use ($param){
                $query->whereIn("type", [3]);
                if(!empty($param['time'])){
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("order_id",'like', '%'.$param["word"].'%');
                if(!empty($param["number"])) $query->where("number",'like', '%'.$param["number"].'%');
            })
            ->order("id", "desc")
            ->page($param['page'], $param['limit'])
            ->select()->toArray();

        $data["count"] = self::field ("*")
            ->whereNull("delete_time")
            ->where(function ($query) use ($param){
                $query->whereIn("type", [3]);
                if(!empty($param['time'])){
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("order_id",'like', '%'.$param["word"].'%');
                if(!empty($param["number"])) $query->where("number",'like', '%'.$param["number"].'%');
            })
            ->count();

        if(!empty($data["data"])){
            foreach ($data["data"] as $key => &$val){
                $val["receiver"] = self::getReceiveGift($val["order_id"]);
            }
        }

        return $data;
    }


    public static function getReceiveGift($order_id = '')
    {
        return self::field("*,FROM_UNIXTIME(create_time) as create_time,FROM_UNIXTIME(act_time) as act_time")
            ->with([
                'user' => function($query) {
                    $query->field("uid,nickname,real_name,phone");
                }
            ])
            ->where("order_id",$order_id)
            ->where("type", 2)
            ->find();
    }


    /**
     * 赠送管理列表 - 详情
     * @param $param
     * @return GiftCardUser|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detailGiftCardShare($param = [])
    {
        $detail = self::field ("*,FROM_UNIXTIME(create_time) as create_time,
                case when type=1 then '购买' 
                    when type=2 then '收到' 
                    when type=3 then '送出' 
                    when type=4 then '订单取消购买' 
                    end as type_text
            ")
            ->with([
                'shareinfo' => function($query) {
                    $query->field("*");
                }
            ])
            ->where("id", $param["id"])
            ->find();

        return $detail;
    }




    public static function bindCardNumber($param = [])
    {
        $reg_find = RecruitPersonageAuthentication::where(["u_id"=>$param["uid"]])->whereNull("delete_at")->find();
        if(empty($reg_find))  throw new Exception("请先实名认证！");
        if(!empty($find["status"])){
            if($find["status"] == 1) {
                throw new Exception("审核中，请实名审核通过后再发布！");
            }else if($find["status"] == 3) {
                throw new Exception("审核未通过，请实名认证审核！");
            }
        }

        $find = self::where("number", $param['number'])->find();
        if(empty($find["number"])) throw new Exception('卡号错误！');
        if($find["status"] == 1) throw new Exception('已激活，不能重复激活！');
        if($find["card_pwd"] != $param["card_pwd"]) throw new Exception('卡密错误！');

        $card_user = GiftCardUser::where("number", $param['number'])->find();
        if(empty($card_user)) throw new Exception('卡信息错误！');

        $user = User::where("uid", $card_user["uid"])->find() ?? [];
        if(empty($user)) throw new Exception('用户信息错误！');

        $length = strlen($user["phone"]);
        $user_phone = substr($user["phone"], $length - 4, 4);
        if($user_phone != $param["phone"]) throw new Exception('密保输入有误！');


        try {
            Db::startTrans();

            $update["status"] = 1;
            $update["act_time"] = time();

            $res = self::where("number", $param['number'])->update($update);
            $res = GiftCardNumber::where("card_number", $param['number'])->update(["status" =>1, "act_uid"=>$param["uid"], "act_time"=>time()]);

            $find = GiftCardNumber::where("card_number", $param['number'])->find() ?? [];

            GiftCardBatch::where("id", $find["card_batch_id"])->inc('act_num', 1)->update();



            //添加余额
            $price_find = self::getGiftCardPrice($param['number']);
            $price_text = $price_find["price"] ?? 0;  //GiftCardUser::where("number", $param['number'])->value("price_text") ?? 0;
            $user = Db::name('user')->where('uid',$param['uid'])->find();
            Db::name('user')->where('uid',$param['uid'])->inc('now_money',$price_text)->update();

            $add = [
                'uid' => $param['uid'],
                'pm' => 1,
                'title' => '礼品卡激活添加余额',
                'category' => 'gift',
                'type' => 'gift_act',
                'number' => $price_text,
                'balance' => $user["now_money"] ?? 0 + $price_text,
                'mark' => '用户礼品卡激活添加余额'.$price_text.'元',
                'add_time' => time(),
            ];
            UserBill::create($add);

            $add2 = [
                'uid' => $param['uid'],
                'link_id' => 2,
                'type' => 'gift_act',
                'title' => '礼品卡激活添加余额',
                'number' => $price_text,
                'balance' => $user["now_money"] ?? 0 + $price_text,
                'pm' => 1,
                'mark' => '用户礼品卡激活添加余额'.$price_text.'元',
                'add_time' => time(),
            ];
            UserMoney::create($add2);


            Db::commit();
        }catch (\Throwable $e){
            Db::rollback();
            Throw new Exception($e->getMessage());
        }
        return $res;
    }




    public static function getGiftCardPrice($number = '')
    {
        return self::alias("a")
            ->field("a.*,FROM_UNIXTIME(a.create_time) as create_time,b.id as bid,b.price,b.original_price,b.subscript_price")
            ->join('gift_card b', 'a.gift_card_id=b.id','left')
            ->where("a.number", $number)
            ->find() ?? [];
    }




}